// import vue from '@/main';
import { sendChat, getChatHistory } from '@/api/api'
import { Message, Notification } from 'element-ui'
const state = {
    loginStatus: localStorage.getItem('doctor_token') || null,
    token: localStorage.getItem('doctor_token') || '',
    messageList: {

    }, // 消息列表， key 问诊id  value未读消息
    newMessage: {

    }
};
const mutations = {
    SET_DOCTOR_STATUS(state, data) {
        state.loginStatus = data
    },
    SET_DOCTOR_TOKEN(state, token) {
        state.token = token
    },
    pushMessage(state, data) {
        if (!Array.isArray(data)) {
            data = [data];
        }
        let flag = false;
        for (const item of data) {
            const { inquiryid } = item;
            if (!inquiryid) {
                continue;
            }
            if (!state.messageList[inquiryid]) {
                flag = true;
            }
            state.messageList[inquiryid] = state.messageList[inquiryid] || [];
            state.messageList[inquiryid].push(item);
            state.newMessage[inquiryid] = true;
            console.log(state.messageList)
        }
        if (flag) {
            Notification.success({
                title: '消息',
                message: '您有新的问诊'
            });
        }
    },
    editeMessage(state, inquiryid) {
        delete state.newMessage[inquiryid];
    }
};
const actions = {
    // 发送消息
    sendMessage(context, data) {
        sendChat(data).then((result) => {
            if (result.code === 200) {
                context.commit('pushMessage', data);
                // callback(null, data);
            } else {
                Message.error('消息发送失败');
                // callback(false, null);
            }
        }).catch(() => {
            Message.error('消息发送失败');
            // callback(err, null);
        });
    },
    getInquiryMessage(context, inquiryIdList = []) {
        if (inquiryIdList.length === 0) return;
        getChatHistory(inquiryIdList).then((result) => {
            context.commit('pushMessage', result.data);
        }).catch((err) => {
            console.log(err);
            Message.error('消息加载失败');
        });
    }
};
const getters = {

};

export default {
    namespaced: true,
    state,
    mutations,
    actions,
    getters
}
